/*
 * @Author: mat
 * @Date: 2020-07-13 06:31:24
 * @LastEditTime: 2021-09-09 17:57:47
 * @Description: 图层添加方法
 */
import { mercator2LonLat } from '@/utils/common';
// 相机移动事件
let placeNameService = null;

// 添加图层
/**
 * @description: 添加图层
 * @param changeBaseImg {Boolean} 是否替换底图
 * @param raisePlaceName {Boolean} 是否将地名图层移至顶部
 * @return:
 */
function addLayer(option, changeBaseImg = false, raisePlaceName = true) {
	// 如果已加载该图层就返回
	if (option.layer) {
		let filterLayers = viewer.imageryLayers._layers.filter(function (layer) {
			return layer._imageryProvider._layer === option.layer;
		});
		if (filterLayers.length > 0) {
			console.log('已加载过' + option.layer);
			return;
		}
	}
	if (changeBaseImg) {
		removeLayerByName('基础影像');
	}
	let layer;
	switch (option.type.toLowerCase()) {
		case 'tms':
			layer = addTMSLayer(option);
			break;
		case 'wmts':
			layer = addWMTSLayer(option);
			break;
		case 'urltemp':
			layer = addURLTempLayer(option);
			break;
		case 'wms':
			layer = addWMSLayer(option);
			break;
		case 'singletile':
			layer = addSingleTileImageLayer(option);
			break;
		default:
			break;
	}
	if (raisePlaceName) {
		raiseLayerToTopByName('地名标注');
	}
	return layer;
}
// 指定url的format模版添加图层
function addURLTempLayer(option) {
	if (option.projection && option.projection == 'custom') {
		let webMercatorProjection = new Cesium.WebMercatorProjection();

		let SouthwestInMeters = webMercatorProjection.project(Cesium.Cartographic.fromDegrees(option.projectionRectangle[1], option.projectionRectangle[0]));
		let NortheastInMeters = webMercatorProjection.project(Cesium.Cartographic.fromDegrees(option.projectionRectangle[3], option.projectionRectangle[2]));

		let layerOption = {
			url: option.url ? option.url : '',
			tileMatrixSetID: option.tileMatrixSetID ? option.tileMatrixSetID : 'EPSG:4326',
			maximumLevel: 0,
			tilingScheme: new Cesium.WebMercatorTilingScheme({
				rectangleSouthwestInMeters: new Cesium.Cartesian2(SouthwestInMeters.x, SouthwestInMeters.y),
				rectangleNortheastInMeters: new Cesium.Cartesian2(NortheastInMeters.x, NortheastInMeters.y),
			}),
		};
		var _layer = viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider(layerOption));
		_layer.name = option.name ? option.name : '';
	} else {
		var _layer = viewer.imageryLayers.addImageryProvider(
			new Cesium.UrlTemplateImageryProvider({
				url: option.url ? option.url : '',
				maximumLevel: option.maximumLevel ? option.maximumLevel : 19,
			})
		);
		_layer.name = option.name ? option.name : '';
	}

	return _layer;
}

// TMS
function addTMSLayer(option) {
	let _layer = viewer.imageryLayers.addImageryProvider(
		new Cesium.createTileMapServiceImageryProvider({
			url: option.url ? option.url : '',
			tilingScheme: new Cesium.GeographicTilingScheme(), // 地图平铺方案，前面墨卡托，后面平铺 WebMercatorTilingScheme  GeographicTilingScheme
		})
	);
	_layer.name = option.name ? option.name : '';
	return _layer;
}
// MWTS
function addWMTSLayer(option) {
	let layerOption = {
		url: option.url ? option.url : '',
		layer: option.layer ? option.layer : '',
		style: 'default',
		format: option.format ? option.format : 'image/jpeg',
		tileMatrixSetID: option.tileMatrixSetID ? option.tileMatrixSetID : 'EPSG:4326',
		tilingScheme: option.tileMatrixSetID === 'EPSG:4326' ? new Cesium.GeographicTilingScheme() : new Cesium.WebMercatorTilingScheme(),
		maximumLevel: option.maximumLevel ? option.maximumLevel : 19,
	};
	if (option.minimumLevel) {
		layerOption['minimumLevel'] = option.minimumLevel;
	}
	if (option.rectangle) {
		layerOption['rectangle'] = new Cesium.Rectangle.fromDegrees(option.rectangle[0], option.rectangle[1], option.rectangle[2], option.rectangle[3]);
	}
	// 部分数据为墨卡托坐标系，转换为经纬度范围
	if (option.mercatorRectangle) {
		let lbPos = mercator2LonLat([option.mercatorRectangle.minX, option.mercatorRectangle.minY]);
		let rtPos = mercator2LonLat([option.mercatorRectangle.maxX, option.mercatorRectangle.maxY]);
		layerOption['rectangle'] = new Cesium.Rectangle.fromDegrees(lbPos[0], lbPos[1], rtPos[0], rtPos[1]);
	}
	let _layer = viewer.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider(layerOption));
	_layer.name = option.name ? option.name : '';
	return _layer;
}
// WMS
function addWMSLayer(option) {
	if (option.rectangle) {
		option['rectangle'] = new Cesium.Rectangle.fromDegrees(option.rectangle[0], option.rectangle[1], option.rectangle[2], option.rectangle[3]);
	}

	let _layer = viewer.imageryLayers.addImageryProvider(
		new Cesium.WebMapServiceImageryProvider({
			url: option.url ? option.url : '',
			layers: option.layer ? option.layer : '',
			parameters: {
				ColorScaleRange: option.ColorScaleRange ? option.ColorScaleRange : '',
				format: 'image/png',
			},
		})
	);

	_layer.alpha = option.alpha ? option.alpha : 1;
	_layer.name = option.name ? option.name : '';
	return _layer;
}
// 单块瓦片类型
function addSingleTileImageLayer(option) {
	let layerOption = {
		url: option.url ? option.url : '',
		tileMatrixSetID: option.tileMatrixSetID ? option.tileMatrixSetID : 'EPSG:4326',
		tilingScheme: option.tileMatrixSetID === 'EPSG:4326' ? new Cesium.GeographicTilingScheme() : new Cesium.WebMercatorTilingScheme(),
	};
	if (option.rectangle) {
		layerOption['rectangle'] = new Cesium.Rectangle.fromDegrees(option.rectangle[0], option.rectangle[1], option.rectangle[2], option.rectangle[3]);
	}
	console.log(layerOption['rectangle']);
	let _layer = viewer.imageryLayers.addImageryProvider(new Cesium.SingleTileImageryProvider(layerOption));
	_layer.name = option.name ? option.name : '';
	return _layer;
}

// 添加地形
function addTerrain(url) {
	let terrainProvider = new Cesium.CesiumTerrainProvider({
		url: url,
		// requestVertexNormals: true,
		// requestWaterMask: true, // 水波纹
	});
	viewer.terrainProvider = terrainProvider;
}

function removeTerrain() {
	viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider({});
}
// 添加3dTiles倾斜模型
function add3DTiles(url) {
	window.tilesetModel = new Cesium.Cesium3DTileset({
		url: url,
		minimumPixelSize: 128,
	});
	window.tilesetModel.readyPromise.then(function (argument) {
		let heightOffset = 80; // 调整倾斜摄影高度，防止飘和进入地下
		let boundingSphere = window.tilesetModel.boundingSphere;
		let cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
		let surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
		let offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
		let translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
		window.tilesetModel.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
		viewer.scene.primitives.add(window.tilesetModel);
		setTimeout(() => {
			viewer.zoomTo(window.tilesetModel);
		}, 500);
	});
}

function remove3DTiles() {
	if (window.tilesetModel) viewer.scene.primitives.remove(window.tilesetModel);
	window.tilesetModel = null;
}
// 根据名称移除图层
function removeLayerByName(name) {
	let layer = viewer.imageryLayers._layers.filter(function (layer) {
		return layer.name === name;
	});
	if (layer[0]) {
		viewer.imageryLayers.remove(layer[0]);
	}
}
// 根据名称将图层移至顶层
function raiseLayerToTopByName(name) {
	let layer = viewer.imageryLayers._layers.filter(function (layer) {
		return layer.name === name;
	});
	if (layer[0]) {
		viewer.imageryLayers.raiseToTop(layer[0]);
	}
}

// 添加矢量地名数据
function addPlaceNameService() {
	if (!placeNameService) placeNameService = new GV.PlaceNameService(viewer, `${g_config.icenter_URL}/placeservice/api/v1/query/dlbm=`);
	else console.log('已经加载过矢量地名');
	placeNameService.visible = true;
}
function removePlaceNameService() {
	if (placeNameService && placeNameService.visible) {
		placeNameService.visible = false;
	}
}
export { addLayer, removeLayerByName, raiseLayerToTopByName, addWMTSLayer, addPlaceNameService, removePlaceNameService, addTerrain, removeTerrain, add3DTiles, remove3DTiles };
